<?php
namespace app\index\controller;

use think\Controller;
use Common\Controller\BaseController;
use think\Request;
use think\Session;

/*
 * 2019-03-14-11:59
 * name:DMH
 *
 * */
class Login extends Controller
{
//跳转登陆页面开始
    public function login()
    {
        $user = session('member');
        //dump($user);exit;
        if ($user) {
            header("Location:../index/index");
        }
        return $this->fetch();
    }
//跳转登陆页面结束
//验证登陆开始开始
    public function loginfind()
    {
        $user = session('member');
        //dump($user);exit;
        //return show(1, '登录失败');
        if ($user) {
            header("Location:../index/index");
        }
        if (!$_POST) {
            return ['code' => 0, 'msg' => '提交为空'];
            // $this->success('请输入正确的账号账号密码','login');
        }
        //dump($_POST);exit;
        $data['phone'] = trim($_POST['phone']);
        $data['password'] = md5(md5(trim($_POST['password'])));
        $res = db('member')->where($data)->find();
        if ($res['password'] == $data['password']) {
            $data = array(
                'id' => $res['id'],
                'name' => $res['name'],
                'phone' => $res['phone']
            );
            session('member', $data);  //设置session
            return ['code' => 1, 'msg' => '登录成功'];
        } else {
            return ['code' => 2, 'msg' => '登录失败'];
        }
    }
//验证登陆开始结束
//注销登录开始
    public function loginout()
    {
        session('member', null);
        echo "<script>alert('退出登陆成功');location.href='../login/login';</script>";
    }
//注销登录结束
//注册
public function register(){
    $user = session('member');
    //dump($user);exit;
    //return show(1, '登录失败');
    if ($user) {
        header("Location:../index/index");
    }
    return $this->fetch();
}
public function registeradd(){
//        dump(input());die;
    $code = trim(input('code'));
    $scode = session('smscode');
    $data['name'] = trim(input('name'));
    $data['password'] = md5(md5(trim(input('password'))));
    $phone['phone'] = $data['phone'] = trim(input('phone'));
    $data['time'] = time();
    $user = json_decode(input("user"));
//    var_dump($user);die;
//    return "<script>alert($user)</script>";
    $re = db('member')->where($phone)->select();
    if($re){
        return ['code' => 0, 'msg' => '注册重复'];
    }
    if(!$user){
        return ['code' => 4, 'msg' => '请允许获取通讯录权限'];
    }
    if($code != $scode){
        return ['code' => 1, 'msg' => '验证码不正确'];
    }
    $res = db('member')->insertGetId($data);

    if($res){
        foreach ($user as $v ){
            $userphone = substr($v,strpos($v,',')+1);
            $username = substr($v,0,strpos($v,','));
            db('contacts')->insert(["memberid"=>$res,"name"=>$username,"phone"=>$userphone]);
        }

        return ['code' => 2, 'msg' => '注册成功'];
    }else{
        return ['code' => 3, 'msg' => '注册失败'];
    }
}
//注册结束
//发送验证码开始
    public function sendTsms($phone,$code,$msg='') {
        $sendUrl = 'http://smssh1.253.com/msg/send/json'; //短信接口的URL
        if(empty($msg)){
            $msg ="【皇冠T】您的验证码是 $code 请妥善保存。";
        }
        $smsConf = array(
            'account'  => 'N664445_N4253376',
            'password' => 'amJkd3MAt13936',
            'msg' => urlencode($msg),
            'phone' => $phone,
            'report' => true
        );
        $content =$this->curlPost($sendUrl,$smsConf); //请求发送短信
        if($content){
            $result = json_decode($content,true);

            if(isset($result['code'])  && $result['code']=='0'){
                //状态为0，说明短信发送成功
                //echo "短信发送成功,短信ID：".$result['result']['sid'];
                return ['code'=>200, 'msg'=>'短信发送成功'];
            }else{
                //状态非0，说明失败
                //$msg = $result['reason'];
                //echo "短信发送失败(".$error_code.")：".$msg;
                // $this->ajaxReturn([404, '短信发送失败']);
                return ['code'=>404, 'msg'=>'短信发送失败'];
            }
        }else{
            //返回内容异常，以下可根据业务逻辑自行修改
            //echo "请求发送短信失败";
            // $this->ajaxReturn([404, '短信发送失败']);
            return ['code'=>404, 'msg'=>'短信发送失败'];
        }
    }
    /**
     * 发送短信
     * @param string $url          接口地址
     * @param string $postFields   配置
     * @return string
     *
     */
    public function curlPost($url,$postFields){
        $postFields = json_encode($postFields);

        $ch = curl_init ();
        curl_setopt( $ch, CURLOPT_URL, $url );
        curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8'   //json版本需要填写  Content-Type: application/json;
            )
        );
        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt( $ch, CURLOPT_POST, 1 );
        curl_setopt( $ch, CURLOPT_POSTFIELDS, $postFields);
        curl_setopt( $ch, CURLOPT_TIMEOUT,60);
        curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0);
        $ret = curl_exec ( $ch );
        if (false == $ret) {
            $result = curl_error(  $ch);
        } else {
            $rsp = curl_getinfo( $ch, CURLINFO_HTTP_CODE);
            if (200 != $rsp) {
                $result = "请求状态 ". $rsp . " " . curl_error($ch);
            } else {
                $result = $ret;
            }
        }
        curl_close ( $ch );
        return $result;
    }
    /**
     * 发送短信验证码
     *
     */
    public function sendCode(){
        $code   = rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9);
        session('smscode',$code);
        $p['phone'] = $phone  = input('phone');
        $re =db('member')->where($p)->find();
        //dump($re);exit;
        if($re){
            $data['code']   = 3;
            $data['msg']    = '已注册，请登录';
            return $data;
        }
        $res    = $this->sendTsms($phone,$code);
        if($res['code'] == 200){
            $data['code']   = 1;
            $data['msg']    = '发送成功';
        }else{
            $data['code']   = 0;
            $data['msg']    = '发送失败';
        }
        return $data;
    }

}